const app = getApp();
const db = wx.cloud.database();

Page({
  data: {
    activities: [],
    filteredActivities: [], // 新增单独的数据字段
    currentTab: 'all',
    showCreateModal: false,
    joining: false, // 添加防重复点击状态
    activityForm: {
      title: '',
      date: '',
      time: '',
      description: ''
    },
    today: new Date().toISOString().split('T')[0]
  },

  onLoad() {
    console.log('当前用户ID:', app.userInfo?._id); // 调试用户信息
    this.loadActivities();
  },
   // 更新筛选方法
  updateFilteredActivities() {
    const { currentTab, activities } = this.data;
    const userId = app.userInfo?._id || '';
    
    let filtered = [];
    if (currentTab === 'all') {
      filtered = activities;
    } else {
      filtered = activities.filter(item => {
        return item.participants && item.participants.includes(userId);
      });
    }
    
    this.setData({ filteredActivities: filtered });
    console.log('筛选后的活动:', filtered); // 调试输出
  },

  // 切换选项卡
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (this.data.currentTab === tab) return;
    
    this.setData({
      currentTab: tab
    }, () => {
      this.updateFilteredActivities();
    });
  },

  // 加载活动列表
  loadActivities() {
    wx.showLoading({ title: '加载中...' });
    wx.cloud.callFunction({
      name: 'getActivities',
      success: async res => {
        console.log('获取到的活动数据:', res.result.data);
        
        // 获取所有参与者头像信息
        const activitiesWithAvatars = await this.getParticipantsAvatars(res.result.data || []);
        
        this.setData({
          activities: activitiesWithAvatars
        }, () => {
          this.updateFilteredActivities();
          wx.hideLoading();
        });
      },
      fail: err => {
        console.error('获取活动失败:', err);
        wx.hideLoading();
        wx.showToast({ title: '加载失败', icon: 'none' });
      }
    });
  },
  
  // 新增方法：获取参与者头像
  async getParticipantsAvatars(activities) {
    // 收集所有需要查询的用户ID
    const allUserIds = [];
    activities.forEach(activity => {
      if (activity.participants) {
        allUserIds.push(...activity.participants);
      }
    });
    
    // 去重
    const uniqueUserIds = [...new Set(allUserIds)];
    
    if (uniqueUserIds.length === 0) {
      return activities.map(activity => ({
        ...activity,
        participantsAvatars: []
      }));
    }
    
    // 批量查询用户信息
    const { data: users } = await db.collection('users')
      .where({
        _id: db.command.in(uniqueUserIds)
      })
      .field({
        _id: true,
        userPhoto: true
      })
      .get();
    
    // 创建用户ID到头像的映射
    const userAvatarMap = {};
    users.forEach(user => {
      userAvatarMap[user._id] = user.userPhoto;
    });
    
    // 为每个活动添加参与者头像数组
    return activities.map(activity => {
      const avatars = activity.participants 
        ? activity.participants.map(id => userAvatarMap[id]).filter(Boolean)
        : [];
      return {
        ...activity,
        participantsAvatars: avatars
      };
    });
  },

  // 显示创建弹窗
  showCreateModal() {
    this.setData({ showCreateModal: true });
  },

  // 隐藏创建弹窗
  hideCreateModal() {
    this.setData({ 
      showCreateModal: false,
      activityForm: {
        title: '',
        date: '',
        time: '',
        description: ''
      }
    });
  },

  // 表单处理
  inputTitle(e) {
    this.setData({ 'activityForm.title': e.detail.value });
  },
  changeDate(e) {
    this.setData({ 'activityForm.date': e.detail.value });
  },
  changeTime(e) {
    this.setData({ 'activityForm.time': e.detail.value });
  },
  inputDesc(e) {
    this.setData({ 'activityForm.description': e.detail.value });
  },

  // 提交新活动
  submitActivity() {
    const { title, date, time, description } = this.data.activityForm;
    if (!title || !date || !time) {
      return wx.showToast({ title: '请填写完整信息', icon: 'none' });
    }

    wx.cloud.callFunction({
      name: 'createActivity',
      data: {
        title,
        time: `${date} ${time}`,
        description,
        creator: app.userInfo.nickName,
        creatorAvatar: app.userInfo.userPhoto
      },
      success: () => {
        wx.showToast({ title: '创建成功' });
        this.hideCreateModal();
        this.loadActivities();
      }
    });
  },

  // 报名/取消报名
  handleJoin(e) {
    if (this.data.joining) return;
    this.setData({ joining: true });
    
    const activityId = e.currentTarget.dataset.id;
    const activity = this.data.activities.find(a => a._id === activityId);
    const isJoined = activity.participants?.includes(app.userInfo._id);
  
    wx.cloud.callFunction({
      name: 'joinActivity',
      data: {
        activityId,
        userId: app.userInfo._id,
        action: isJoined ? 'leave' : 'join'
      },
      complete: () => {
        this.setData({ joining: false });
      },
      success: async (res) => {
        if (res.result.success) {
          wx.showToast({ 
            title: isJoined ? '已取消报名' : '报名成功',
            icon: 'success'
          });
          
          // 更新参与者列表
          const updatedActivities = this.data.activities.map(item => {
            if (item._id === activityId) {
              return {
                ...item,
                participants: res.result.updatedParticipants
              };
            }
            return item;
          });
          
          // 重新获取参与者头像
          const activitiesWithAvatars = await this.getParticipantsAvatars(updatedActivities);
          
          this.setData({ 
            activities: activitiesWithAvatars,
            filteredActivities: this.updateFilteredActivities(activitiesWithAvatars)
          });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '操作失败', icon: 'none' });
        console.error(err);
      }
    });
  },

  // 判断是否已报名
  isJoined(activity) {
    return activity.participants?.includes(app.userInfo._id);
  }
});